﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Loong.Store
{
    /// <summary>
    /// 将文件存储到
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ObjectToFile<T>
    {
        private string filename;
        private IFormatter formatter;

        public ObjectToFile(string filename)
        {
            this.filename=filename;
            formatter = new BinaryFormatter();
        }


        public void Write(T item)
        {
            
            Stream stream = new FileStream(filename, FileMode.OpenOrCreate,FileAccess.Write, FileShare.None);
            formatter.Serialize(stream, item);
            stream.Close();
 
        }

        public T Read()
        {
            Stream stream2 = new FileStream(this.filename, FileMode.Open,  FileAccess.Read, FileShare.None);
            T o=  (T)formatter.Deserialize(stream2);
            stream2.Close();
            return o;
        }
    }
}
